<template>
    <div class="list-wrapper">
        <Block>
            <DataGrid :auto-load="autoLoad" row-key="id" border ref="dataGridRef">
                <template #toolbar-search>
                    <div class="query-from-box">
                        <el-form>
                            <el-form-item>
                                <el-input v-model="queryData.appName" placeholder="应用名称/标识符" clearable />
                            </el-form-item>
                            <el-form-item>
                                <el-select v-model="queryData.status" placeholder="状态" clearable>
                                    <el-option
                                        v-for="(value, key) in sys_normal_disable"
                                        :label="value.label"
                                        :key="key"
                                        :value="value.value"
                                    />
                                </el-select>
                            </el-form-item>
                            <el-form-item>
                                <el-date-picker
                                    v-model="queryData.createTime"
                                    type="daterange"
                                    value-format="YYYY-MM-DD HH:mm:ss"
                                    range-separator="-"
                                    start-placeholder="创建时间（开始"
                                    end-placeholder="结束日期）"
                                    :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
                                />
                            </el-form-item>
                        </el-form>
                    </div>
                </template>
                <template #toolbar-operation>
                    <el-button type="primary" @click="operCollect('创建')">新建</el-button>
                </template>
                <el-table-column type="index" label="序号" width="60" align="center" fixed />
                <el-table-column label="应用名称" width="150" show-overflow-tooltip fixed>
                    <template #default="scope">
                        <el-button link type="primary" @click="operCollect('详情', scope.row)">
                            {{ scope.row.appName }}
                        </el-button>
                    </template>
                </el-table-column>
                <el-table-column prop="appCode" label="标识符" show-overflow-tooltip />
                <el-table-column prop="seq" label="排序" width="60" />
                <el-table-column prop="address" label="地址" show-overflow-tooltip>
                    <template #default="scope">
                        <el-link :href="scope.row.address" target="_blank" underline>{{ scope.row.address }}</el-link>
                    </template>
                </el-table-column>
                <el-table-column label="状态">
                    <template #default="scope">
                        <el-switch
                            v-if="scope.row.status == '1' || scope.row.status == '0'"
                            v-model="scope.row.status"
                            active-value="0"
                            inactive-value="1"
                            :before-change="() => operCollect('激活', scope.row) as Promise<boolean>"
                        ></el-switch>
                    </template>
                </el-table-column>
                <el-table-column prop="createTime" width="190" label="创建时间" show-overflow-tooltip />
                <el-table-column label="操作" width="135" fixed="right">
                    <template #default="scope">
                        <el-button
                            link
                            type="primary"
                            @click="operCollect('修改', scope.row)"
                            v-if="scope.row.status === '1'"
                        >
                            修改
                        </el-button>
                        <el-button
                            link
                            type="danger"
                            @click="operCollect('删除', scope.row)"
                            v-if="scope.row.status === '1'"
                        >
                            删除
                        </el-button>
                        <el-text v-else class="mx-1" size="small">仅停用状态可操作</el-text>
                    </template>
                </el-table-column>
            </DataGrid>
        </Block>
    </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import type { AppQuery } from '@great/services';
import { systemAppService } from '@great/services';
import { showPopupBox } from '@great/utils';
import DialogModal from './components/DialogModal.vue';
import { Block, DataGrid, type DataGridInstance } from '@great/components';
import { checkPermi } from '@/utils/ruoyi';

const { proxy } = getCurrentInstance() as any;
const { sys_normal_disable } = toRefs<any>(proxy?.useDict('sys_normal_disable'));

// 查询条件
const queryData = ref({
    appName: '',
    appCode: '',
    status: '',
    createTime: [] as string[]
});
const dataGridRef = useTemplateRef<DataGridInstance>('dataGridRef');
const autoLoad = reactive({
    debounce: true,
    reloadDeps: [queryData],
    onLoad: async (current, size) => {
        const res: any = await systemAppService.listApp(
            proxy?.addDateRange(
                {
                    pageNum: current,
                    pageSize: size,
                    status: queryData.value.status,
                    appKey: queryData.value.appName
                },
                queryData.value.createTime
            ) as AppQuery
        );
        return { data: res.rows, total: res.total };
    }
});

/**
 * 操作收集
 * @param type 操作类型
 * @param row 操作行数据
 */
const operCollect = async (type: string, row?: any) => {
    switch (type) {
        case '创建':
            showPopupBox(DialogModal, {
                getList: dataGridRef.value?.reset as () => Promise<void>
            });
            break;
        case '详情':
            if (checkPermi(['system:app:detail'])) {
                showPopupBox(DialogModal, {
                    row,
                    readonly: true
                });
            }
            break;
        case '修改':
            showPopupBox(DialogModal, {
                row,
                getList: dataGridRef.value?.refresh as () => Promise<void>
            });
            break;
        case '删除':
            ElMessageBox.confirm(`确认删除应用${row?.appName || ''}吗？`, '提示', {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning'
            })
                .then(async () => {
                    await systemAppService.delApp(row?.appId as number);
                    ElNotification({
                        title: '删除成功！',
                        type: 'success'
                    });
                    dataGridRef.value?.refresh();
                })
                .catch(() => {});
            break;
        case '激活':
            return new Promise((resolve, reject) => {
                ElMessageBox.confirm(`确认${['关闭', '打开'][row.status]}应用${row?.appName || ''}吗？`, '提示', {
                    confirmButtonText: '确认',
                    cancelButtonText: '取消',
                    type: 'warning'
                })
                    .then(async () => {
                        await systemAppService.changeStatus(row.appId, row.status == '1' ? '0' : '1');
                        ElNotification({
                            title: `${['关闭', '打开'][row.status]}成功！`,
                            type: 'success'
                        });
                        dataGridRef.value?.refresh();
                        resolve(true);
                    })
                    .catch(() => {
                        resolve(false);
                    });
            });

            break;
    }
};
</script>
<style scoped lang="scss">
.list-wrapper {
    .query-from-box {
        display: flex;
        align-items: center;
        .el-form {
            display: flex;
            .el-form-item {
                margin-bottom: 0;
                width: 100px;
                &:first-of-type {
                    width: 130px;
                }
                &:last-of-type {
                    width: 240px;
                }
            }
            .el-form-item + .el-form-item {
                margin-left: 10px;
            }
        }
    }
    :deep(.data-grid) {
        .table-item-status {
            display: flex;
            align-items: center;
            &::before {
                content: '';
                width: 6px;
                height: 6px;
                display: inline-block;
                border-radius: 50%;
                margin-right: 5px;
            }
        }
        .table-item-status[status='未激活'] {
            &::before {
                background-color: #909399;
            }
        }
        .table-item-status[status='激活'] {
            &::before {
                background-color: #67c23a;
            }
        }
    }
}
</style>
